package com.enation.app.javashop.core.distribution.service.pattern;


import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.dos.DistributionGoods;
import com.enation.app.javashop.core.distribution.model.dos.DistributionOrderDO;
import com.enation.app.javashop.core.distribution.model.enums.DistributionConstants;
import com.enation.app.javashop.core.distribution.service.DistributionGoodsManager;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.member.model.dos.MemberInviter;
import com.enation.app.javashop.core.member.service.MemberInviterManager;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanOrderDO;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanOrderManager;
import com.enation.app.javashop.core.statistics.util.DateUtil;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.core.trade.order.model.dos.OrderItemsDO;
import com.enation.app.javashop.core.trade.order.model.enums.OrderTypeEnum;
import com.enation.app.javashop.core.trade.order.model.enums.ShipTypeEnum;
import com.enation.app.javashop.core.trade.order.service.OrderQueryManager;
import com.enation.app.javashop.framework.context.ApplicationContextHolder;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.util.CurrencyUtil;
import com.enation.app.javashop.framework.util.DictUtils;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.List;

/**
 * 聚焦团长策略
 */
public class DistributionMemberFocusStrategy implements DistributionStrategy{

    protected final Log logger = LogFactory.getLog(this.getClass());

    private static DistributionManager distributionManager;
    private static MemberInviterManager memberInviterManager;
    private static OrderQueryManager orderQueryManager;
    private static ShetuanGoodsManager shetuanGoodsManager;
    private static ShetuanManager shetuanManager;
    private static ShetuanOrderManager shetuanOrderManager;
    private static DistributionGoodsManager distributionGoodsManager;
    private static DaoSupport tradeDaoSupport;

    static {
        distributionManager = ApplicationContextHolder.getBean(DistributionManager.class);
        memberInviterManager = ApplicationContextHolder.getBean(MemberInviterManager.class);
        orderQueryManager = ApplicationContextHolder.getBean(OrderQueryManager.class);
        shetuanGoodsManager = ApplicationContextHolder.getBean(ShetuanGoodsManager.class);
        shetuanManager = ApplicationContextHolder.getBean(ShetuanManager.class);
        shetuanOrderManager = ApplicationContextHolder.getBean(ShetuanOrderManager.class);
        distributionGoodsManager = ApplicationContextHolder.getBean(DistributionGoodsManager.class);
        tradeDaoSupport = (DaoSupport) ApplicationContextHolder.getBean("tradeDaoSupport");
    }


    /**
     * 决定收益人
     */
    @Override
    public void distributors(OrderDO orderDO, DistributionOrderDO distributionOrderDO) {
        int buyMemberId = orderDO.getMemberId();
        DistributionDO distributor = distributionManager.getDistributorByMemberId(buyMemberId);
        // 如果自己是分销商 一级分销佣金自己得 二级分销佣金一级分销得
        if(distributor.getAuditStatus() == 2 && distributor.getStatus() == 1){
            // 设置一级分销佣金所得者
            distributionOrderDO.setMemberIdLv1(buyMemberId);
            // 设置补贴所得者
            distributionOrderDO.setSubsidyMemberId(buyMemberId);
            // 设置二级分销佣金所得者
            Integer memberIdLv1 = distributor.getMemberIdLv1();
            if(memberIdLv1 != null){
                DistributionDO lv1Distributor = distributionManager.getDistributorByMemberId(memberIdLv1);
                if(lv1Distributor != null && lv1Distributor.getAuditStatus() == 2 && lv1Distributor.getStatus() == 1){
                    distributionOrderDO.setMemberIdLv2(memberIdLv1);
                }else{
                    // 如果上级分销是空的 就取平台
                    distributionOrderDO.setMemberIdLv2(-1); // -1表示结算给平台
                }
            }else{
                // 如果上级分销是空的 就取平台
                distributionOrderDO.setMemberIdLv2(-1); // -1表示结算给平台
            }
        }else{
            // 设置一级分销佣金所得者
            Integer memberIdLv1 = distributor.getMemberIdLv1();
            DistributionDO lv1Distributor = null;
            if(memberIdLv1 != null){
                lv1Distributor = distributionManager.getDistributorByMemberId(memberIdLv1);
            }
            if(lv1Distributor != null && lv1Distributor.getAuditStatus() == 2 && lv1Distributor.getStatus() == 1){
                // 设置一级分销佣金所得者
                distributionOrderDO.setMemberIdLv1(memberIdLv1);
                // 设置补贴所得者
                distributionOrderDO.setSubsidyMemberId(memberIdLv1);

                // 设置二级分销佣金所得者
                Integer memberIdLv2 = lv1Distributor.getMemberIdLv1();
                if(memberIdLv2 != null){
                    DistributionDO lv2Distributor = distributionManager.getDistributorByMemberId(memberIdLv2);
                    if(lv2Distributor != null && lv2Distributor.getAuditStatus() == 2 && lv2Distributor.getStatus() == 1){
                        distributionOrderDO.setMemberIdLv2(memberIdLv2);
                    }else{
                        // 如果二级分销不可用 就取平台
                        distributionOrderDO.setMemberIdLv2(-1); // -1表示结算给平台
                    }
                }else{
                    // 如果一级分销的上级分销是空的 就取平台
                    distributionOrderDO.setMemberIdLv2(-1); // -1表示结算给平台
                }

                // 更新最新下单时间刷新
                distributor.setLv1ExpireTime(DateUtil.getDateline() + DistributionConstants.EXPIRE_TIME);
                distributor.setLastOrderTime(orderDO.getCreateTime());
                distributionManager.edit(distributor);
            }

            // 如果商城订单没有一级分销 结算给平台
            String orderType = orderDO.getOrderType();
            if(distributionOrderDO.getMemberIdLv1() == null && OrderTypeEnum.normal.name().equals(orderType)){
                distributionOrderDO.setMemberIdLv1(-1);
                distributionOrderDO.setMemberIdLv2(-1);
            }
        }

        // 设置邀请人会员id
        MemberInviter memberInviter = memberInviterManager.getByMemberId(buyMemberId);
        if(memberInviter != null){
            distributionOrderDO.setInviterMemberId(memberInviter.getInviterMemberId());
        }
    }


    /**
     * 计算收益
     */
    @Override
    public void countProfit(OrderDO orderDO, DistributionOrderDO distributionOrderDO) {
        Double lv1Money = 0.0;
        Double lv2Money = 0.0;
        Double inviteMoney = 0.0;
        Double subsidyMoney = 0.0;

        Integer memberIdLv1 = distributionOrderDO.getMemberIdLv1();
        Integer memberIdLv2 = distributionOrderDO.getMemberIdLv2();
        Integer inviterMemberId = distributionOrderDO.getInviterMemberId();
        Integer subsidyMemberId = distributionOrderDO.getSubsidyMemberId();

        // 判断是否是衢山订单
        boolean isQuShanOrder = false;
        double quShanFirstRate = 0.0;
        double qushanSelfRaisingRate = 0.0;
        String judgeCondition = orderDO.getShipAddr() + orderDO.getPickAddr();
        logger.info("衢山订单判断条件:" + judgeCondition);
        /*if(isQuShanOrder = (judgeCondition.contains("衢山") && !judgeCondition.contains("衢山大道"))){
            String quShanFirstRateString = DictUtils.getDictValue("", "qushan_first_rate", "qushan_first_rate");
            if(!StringUtil.isEmpty(quShanFirstRateString)){
                try {
                    quShanFirstRate = Double.valueOf(quShanFirstRateString);
                }catch (Exception e){
                    logger.error("一级团长佣金比例设置失败", e);
                }
            }
            String qushanSelfRaisingRateString = DictUtils.getDictValue("", "qushan_self_raising_rate", "qushan_self_raising_rate");
            if(!StringUtil.isEmpty(qushanSelfRaisingRateString)){
                try {
                    qushanSelfRaisingRate = Double.valueOf(qushanSelfRaisingRateString);
                }catch (Exception e){
                    logger.error("自提点佣金比例设置失败", e);
                }
            }
        }*/

        List<OrderItemsDO> orderItems = orderQueryManager.getOrderItems(orderDO.getSn());

        String orderType = orderDO.getOrderType();
        if(orderType.equals(OrderTypeEnum.shetuan.name()) || orderType.equals(OrderTypeEnum.pintuan.name())){
            Double selfRaisingMoney = 0.0;
            int buyNum = 0;
            ShetuanDO shetuan = null;

            for (OrderItemsDO orderItemsDO : orderItems) {
                buyNum = orderItemsDO.getNum();
                // 此商品实际付款金额
                Double actualPayMoney = orderItemsDO.getRefundPrice();
                actualPayMoney = actualPayMoney == null ? 0.0 : actualPayMoney;

                // 查询社团商品
                ShetuanGoodsDO shetuanGoodsDO = shetuanGoodsManager.getById(orderItemsDO.getShetuanGoodsId());
                if(shetuanGoodsDO == null){
                    logger.debug("社团商品查询为空，社团商品id为" + orderItemsDO.getShetuanGoodsId());
                    shetuanGoodsDO = new ShetuanGoodsDO();
                    shetuanGoodsDO.setFirstRate(8.0);
                    shetuanGoodsDO.setSecondRate(2.0);
                    shetuanGoodsDO.setInviteRate(0.0);
                    shetuanGoodsDO.setSelfRaisingRate(2.0);
                }
                if(shetuan == null && shetuanGoodsDO.getShetuanId() != null){
                    shetuan = shetuanManager.getShetuanById(shetuanGoodsDO.getShetuanId());
                }

                // 如果是衢山订单并且不是助农订单 修改佣金比例
                String goodsName = orderItemsDO.getName();
                if(isQuShanOrder && goodsName != null && !goodsName.contains("助农")){
                    logger.info("衢山订单，已自动调整比例：" + quShanFirstRate + "," + qushanSelfRaisingRate);
                    shetuanGoodsDO.setFirstRate(quShanFirstRate);
                    shetuanGoodsDO.setSelfRaisingRate(qushanSelfRaisingRate);
                }

                // 计算一级佣金
                Double firstRate = shetuanGoodsDO.getFirstRate();
                if(memberIdLv1 != null && firstRate != null){
                    lv1Money = CurrencyUtil.add(lv1Money, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(firstRate, 100)));
                }

                // 计算二级佣金
                Double secondRate = shetuanGoodsDO.getSecondRate();
                if(memberIdLv2 != null && secondRate != null){
                    lv2Money = CurrencyUtil.add(lv2Money, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(secondRate, 100)));
                }

                // 计算邀请佣金
                Double inviteRate = shetuanGoodsDO.getInviteRate();
                if(inviterMemberId != null && inviteRate != null){
                    inviteMoney = CurrencyUtil.add(inviteMoney, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(inviteRate, 100)));
                }

                // 计算补贴
                DistributionGoods distributionGoods = distributionGoodsManager.getModel(shetuanGoodsDO.getGoodsId());
                if(subsidyMemberId != null && distributionGoods != null){
                    Double subsidyRate = distributionGoods.getSubsidyRate();
                    if(subsidyRate != null && subsidyRate > 0){
                        subsidyMoney = CurrencyUtil.add(subsidyMoney, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(subsidyRate, 100)));
                    }
                }

                // 自提点佣金
                Double selfRaisingRate = shetuanGoodsDO.getSelfRaisingRate();
                if(selfRaisingRate != null && ShipTypeEnum.SELF.getIndex().equals(orderDO.getShippingType())){
                    selfRaisingMoney = CurrencyUtil.add(selfRaisingMoney, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(selfRaisingRate, 100)));
                }
            }

            //计算团购订单自提点佣金
            ShetuanOrderDO shetuanOrderDO = shetuanOrderManager.getByOrderId(orderDO.getOrderId());
            shetuanOrderDO.setLeaderCommission(selfRaisingMoney);
            shetuanOrderDO.setLeaderReturnCommission(0.0);
            Double orderPrice = orderDO.getOrderPrice();
            if(orderPrice > 0){
                shetuanOrderDO.setCommissionRate(CurrencyUtil.mul(CurrencyUtil.div(selfRaisingMoney, orderPrice), 100));
            }else{
                shetuanOrderDO.setCommissionRate(0.0);
            }
            shetuanOrderDO.setBuyNum(buyNum);
            if(shetuan == null){
                shetuanOrderDO.setPickTime(com.enation.app.javashop.framework.util.DateUtil.getDateline() + 3600 * 24);
            }else{
                shetuanOrderDO.setPickTime(shetuan.getPickTime());
            }
            shetuanOrderDO.setCommissionType("团长佣金");
            tradeDaoSupport.update(shetuanOrderDO, shetuanOrderDO.getId());
        }else{
            for (OrderItemsDO orderItemsDO : orderItems) {
                // 此商品实际付款金额
                Double actualPayMoney = orderItemsDO.getRefundPrice();

                // 查询分销商品
                DistributionGoods distributionGoods = distributionGoodsManager.getModel(orderItemsDO.getGoodsId());
                if(distributionGoods == null){
                    continue;
                }

                // 计算一级佣金
                Double grade1Rebate = distributionGoods.getGrade1Rebate();
                if(memberIdLv1 != null && grade1Rebate != null){
                    lv1Money = CurrencyUtil.add(lv1Money, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(grade1Rebate, 100)));
                }

                // 计算二级佣金
                Double grade2Rebate = distributionGoods.getGrade2Rebate();
                if(memberIdLv2 != null && grade2Rebate != null){
                    lv2Money = CurrencyUtil.add(lv2Money, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(grade2Rebate, 100)));
                }

                // 计算邀请佣金
                Double inviterRate = distributionGoods.getInviterRate();
                if(inviterMemberId != null && inviterRate != null){
                    inviteMoney = CurrencyUtil.add(inviteMoney, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(inviterRate, 100)));
                }

                // 计算补贴
                Double subsidyRate = distributionGoods.getSubsidyRate();
                if(subsidyMemberId != null && subsidyRate != null){
                    if(subsidyRate > 0){
                        subsidyMoney = CurrencyUtil.add(subsidyMoney, CurrencyUtil.mul(actualPayMoney, CurrencyUtil.div(subsidyRate, 100)));
                    }
                }
            }
        }

        distributionOrderDO.setGrade1Rebate(lv1Money);
        distributionOrderDO.setGrade2Rebate(lv2Money);
        distributionOrderDO.setInviteRebate(inviteMoney);
        distributionOrderDO.setSubsidyRebate(subsidyMoney);

        // 反过来计算比例 因为一个订单中可能有很多的sku或者goods
        Double goodsPrice = orderDO.getGoodsPrice();
        if(goodsPrice > 0){
            distributionOrderDO.setLv1Point(CurrencyUtil.mul(CurrencyUtil.div(lv1Money, goodsPrice), 100));
            distributionOrderDO.setLv2Point(CurrencyUtil.mul(CurrencyUtil.div(lv2Money, goodsPrice), 100));
            distributionOrderDO.setInvitePoint(CurrencyUtil.mul(CurrencyUtil.div(inviteMoney, goodsPrice), 100));
            distributionOrderDO.setSubsidyPoint(CurrencyUtil.mul(CurrencyUtil.div(subsidyMoney, goodsPrice), 100));
        }else{
            distributionOrderDO.setLv1Point(0.0);
            distributionOrderDO.setLv2Point(0.0);
            distributionOrderDO.setInvitePoint(0.0);
            distributionOrderDO.setSubsidyPoint(0.0);
        }
    }

}
